<?php

/**
 * dragon.hu add @2015.12.9  discountshop
 */

defined('BASEPATH') or die('forbidden');

class Discountshop_Controller Extends Controller {

    private $tmpconnect;
    private $costtype;
    private $dynactivityTypeList;
    private $activityinfo; //此活动相关信息，如开始结束时间等
    private $maxday;  //折扣商店最大天数
    
    function _init() {
        check_level(50, segment(0), segment(1, 'index'));
        
        $this->costtype = array('1440600000' => '钻石', '1440700000' => '金币');
        // 得到选择的区号
        $areanum = $_SESSION ['area_selected_id'];
        if ($areanum == '') {
        	echo "<script>alert('" . translate ( 'C_SELECT_AREA_TEXT' ) . "');</script>";
        	return;
        }
        //得到当前的活动
        $area_host = $_SESSION['area_selected_host'];
        $strResult = vpost($area_host . "action=10");
        $row = json_decode($strResult, true);
        
        foreach ($row as $key => $value) 
        {
        	if ($value['activityId'] == 1014) ////1014为限购商城专属活动ID，不得修改！！
        	{
        		$this->activityinfo[] = $value;
        	}
        }
        //var_dump($this->activityinfo);
        //exit();
        
        $tmp_connect = $this->load->database('center_db') or die("load failed!".mysql_error());
        $tmpsql = "SELECT id, name FROM dynamic_type_object ";
        $tmp_connect->query($tmpsql) or die("query failed!".mysql_error());
        while($dynrow = $tmp_connect->get_array()){
        	$this->dynactivityTypeList[$dynrow['id']] = $dynrow['name'];
        }
        
        $this->tmpconnect = getTmpDbConnect ( PLATFORM_ALL, 'all', $areanum, DBTYPE_DYNAMIC );
        $sql = "SELECT MAX(day) AS num FROM dynamic_activity_secretstore";
        $one = $this->tmpconnect->one($sql);
        $this->maxday = $one['num'];
        //var_dump($this->maxday);
        //exit(0);
    }

    function index() {
        $this->view->display("activity/discountshop/index");
    }

    function flexigrid() {
        //读取flexigrid传输的数据
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        
        //$sql = "SELECT * FROM dynamic_activity_secretstore";
        $sql = "SELECT COUNT(*) AS num FROM dynamic_activity_secretstore";
		$one = $this->tmpconnect->one($sql);
		$total = $one['num'];
		$orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "";
			
		$sql = "SELECT {$colsinfo} FROM dynamic_activity_secretstore  where {$where} {$orderby} LIMIT {$offset},{$rp}";
		$this->tmpconnect->query($sql);
		while ($n = $this->tmpconnect->get_array('default'))
		{
			$n['giftid'] = $n['giftid']."(".$this->dynactivityTypeList[$n['giftid']].")";
			$n['cost_id'] = $this->costtype[$n['cost_id']];
			$rows[] = array('id' => $n['id'], 'cell' => $n);
		}
		$result = array(
	            'page' => $page,
	            'total' => $total,
	            'rows' => $rows
		);
		echo json_encode($result);
    }

    function add($id = 0) {
        //是否来源于表单请求
        $sql = "SELECT * FROM dynamic_activity_secretstore";
        $this->tmpconnect->query($sql);
        $tmparr = array();
        while($n = $this->tmpconnect->get_array('default'))
        {
        	$tmparr[$n['subid']][$n['day']][$n['shelfid']] = $n;
        }
        //var_dump($tmparr);
        //exit(0);
        if (is_submit()) {
            $rowdata = $_POST['row'];
            //var_dump($rowdata);
            //exit(0);
            //1.判断day和shelfid
            foreach ($tmparr as $k0 => $v0)
            {
            	if ($k0 == $rowdata['subid'])
            	{
            		foreach ($tmparr as $k1 => $v1)
            		{
            			if ($k1 == $rowdata['day'])
            			{
            				foreach ($v1 as $k2 => $v2)
            				{
            					if ($k2 == $rowdata['shelfid'])
            					{
            						//表示重复了
            						echo "<script>alert('shelfid repeated !!!');</script>";
            						$this->view->assign('costtype',$this->form->select('row[costtype]', $this->costtype, '', array('id'=>'costtype')));
            						$this->view->display("activity/discountshop/add");
            						return ;
            					}
            				}
            			}
            		}
            	}
            }
            
            //2.插入数据库中
            $tmpstr = "INSERT INTO dynamic_activity_secretstore(shelfid, subid, day, cost_id, price, discount, giftid, maxcount) VALUES(".
            $rowdata['shelfid'].", ".$rowdata['subid'].", ".$rowdata['day'].", ".$rowdata['costtype'].", ".
            $rowdata['price'].", ".$rowdata['discount'].", ".$rowdata['giftid'].", ".$rowdata['maxcount'].")";
            $res = $this->tmpconnect->query($tmpstr);
            if ($res)
            {
            	//通知游戏服
            	$area_host = !empty( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
            	$url = $area_host . "action=51&messageid=1014";  //1014为限购商城专属活动ID，不得修改！！！
            	$ret = vpost ( $url, 10 );
            	cp_tips ( 0 == $ret ? "success" : "error" );
            }
            else
            {
            	cp_tips("error");
            }
            
        }
        $this->view->assign('costtype',$this->form->select('row[costtype]', $this->costtype, '', array('id'=>'costtype')));
        $this->view->display("activity/discountshop/add");
    }

    function edit($id = 0) {
        if (empty($id))
            error(translate('C_INVALID_PARAM_ID', $id));
        
        $rowdata = $this->tmpconnect->one("SELECT * FROM dynamic_activity_secretstore WHERE id=$id");
        //var_dump($rowdata);
		if (!is_array($rowdata))
			error(translate('C_INVALID_PARAM_ID', $id));
		$loop = 0;

		$tmpactInfo = array();
		for ($i = 0; $i < count($this->activityinfo); $i++)
		{
			if ($this->activityinfo[$i]['subid'] == $rowdata['subid'])
			{
				$tmpactInfo = $this->activityinfo[$i];
				break;
			}
		}
		$tmpnum = $tmpactInfo['dayreset'];
		if ($tmpnum == 0)
			$tmpnum = 1;
			
		// 算出当前是第几天
		$difday = (time () - $tmpactInfo ['startTime']) / 86400;
		$loop = ceil ( $difday / $tmpnum );  //进行到哪一轮了
	
		$targetday = $loop % $this->maxday;
		if ($targetday == 0)
		{
			$targetday = $this->maxday;
		}
		//var_dump($difday);
		//var_dump($targetday);
		//exit(0);
		
        //是否来源于表单请求
        if (is_submit()) {
        	$rowdata = $_POST['row'];
        	//var_dump($rowdata);
        	//exit(0);
            $sql = "UPDATE dynamic_activity_secretstore SET cost_id =".$rowdata['costtype'].", price=".$rowdata['price'].
            ", discount=".$rowdata['discount'].", giftid=".$rowdata['giftid'].", maxcount=".$rowdata['maxcount']." WHERE id=$id";
            if($this->tmpconnect->query($sql))
            {
            	//通知游戏服
            	$area_host = !empty( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
            	$url = $area_host . "action=51&messageid=1014";  //1014为限购商城专属活动ID，不得修改！！！
            	$ret = vpost ( $url, 10 );
            	cp_tips ( 0 == $ret ? "success" : "error" );
            }
            else
            {
            	cp_tips("error");
            }
        }
        
        $this->view->assign("targetday", $targetday);
        $this->view->assign('costtype',$this->form->select('row[costtype]', $this->costtype, array('costtype' => $rowdata['cost_id']), array('id'=>'costtype')));
        $this->view->display("activity/discountshop/edit", array('row' => $rowdata));
    }  
    
	function del($id = 0)
	{ 
		$c = 0;
		$r = '';
		if ($id === 0)
			json_output($c, translate('C_INVALID_PARAM_ID', $id));
		$row = $this->tmpconnect->one("SELECT * FROM dynamic_activity_secretstore WHERE id=$id");
		if (!is_array($row))
			json_output($c, translate('C_INVALID_PARAM_ID', $id));
		
		if ($this->tmpconnect->delete('dynamic_activity_secretstore', array('id' => $id))) 
		{
			//通知游戏服
			$area_host = !empty( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
			$url = $area_host . "action=51&messageid=1014";  //1014为限购商城专属活动ID，不得修改！！！
			$ret = vpost ( $url, 10 );
			$ret == 0 ? $c = 1 : $r = translate('C_TIPS_ERROR_TEXT');
			insert_log(translate('MENU_MALL_DISCOUNTSHOP'),translate('DEL'), array('id'=> $id));
			//$c = 1;
		} 
		else 
		{
			$r = translate('C_TIPS_ERROR_TEXT');
		}
		json_output($c, $r);
	}
    
}